import { BaseMode } from "./interface";
import { Utils } from "./util";

export class VarTest implements BaseMode{
    run(){
        let util = new Utils();
        //================变量====================
        // for (let i = 0; i < 10 ; i++) {
        //     setTimeout(function() {util.log(i,"let in for setTimeout"); }, 100 * i);
        // }

        //解构数组
        let input = [1, 2];
        let [first, second] = input;
        // swap variables
        [first, second] = [second, first];
        util.log( first,'解构数组first');
        util.log( second,'解构数组second');
        let [first1, ...rest] = [1, 2, 3, 4];
        util.log( first1,'解构数组first1');
        util.log( rest,'解构数组rest');

        //对象解构
        let o = {
            a: "foo",
            b: 12,
            c: "bar"
        }
        // let { c, b } = o;
        // 指定类型
        let {a, b}: {a: string, b: number} = o;
        util.log( a+b,'对象解构c+b');
        let aa,bb;
        ({ bb,aa } = { aa: "baz", bb: 101 });
        util.debug('对象解构aa,bb',  aa,bb);
        let { c,...passthrough } = o;
        let total = passthrough.b + passthrough.a.length;
        util.debug('对象解构',  c,passthrough.b,passthrough.a,total);

        //默认值
        function keepWholeObject(wholeObject: { a: string, b?: number }) {
            let { a, b = 1001 } = wholeObject;
            util.debug('keepWholeObject 默认值', a,b);
        }
        keepWholeObject(o);
        keepWholeObject({a:"1"});

        //类型声明 
        //函数声明
        type C = { a: string, b?: number }//b可选参数
        // function f({ a, b }: C): void {
        //     // ...
        // }
        function f({ a, b = 0 } = { a: "" }): void {
            // ...
            util.debug("函数解构",a,b);
        }
        f({ a: "yes" }) // ok, default b = 0
        f() // ok, default to {a: ""}, which then defaults b = 0
        // f({}) // error, 'a' is required if you supply an argument


        //展开
        let a1 = [1, 2];
        let a2 = [3, 4];
        let bothPlus = [0, ...a1, ...a2, 5];
        util.log(bothPlus,'展开数组');// 展开操作创建了 first和second的一份浅拷贝
        let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };
        let search = { ...defaults, food: "rich" }; 
        util.log(search,'展开对象1');
        search = { food: "rich", ...defaults };
        util.log(search,'展开对象2');
        //对象展开还有其它一些意想不到的限制
        //它只包含自身的可枚举的属性
        class Cls {
            p = 12;
            m() {
            }
        }
        let cls = new Cls();
        let clone = { ...cls };
        util.log(clone,'展开class,会丢失方法');
        clone.p; // ok
        // clone.m(); // error!
    };
}